// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using PfRep.Common;
using System.Collections;

namespace PfRep.DataAccess
{
    /// <summary>
    /// Active Directory data access functions
    /// </summary>
    public static class AD
    {
        /// <summary>
        /// Retrieves AD users starting with the given text
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static ArrayList GetAdUsers(string filter)
        {
            // Connect to the Root DSE
            //DirectoryEntry rootDsePath = new DirectoryEntry("GC://RootDSE");
            DirectoryEntry rootDsePath = new DirectoryEntry("LDAP://RootDSE");
            //DirectoryEntry rootDse = new DirectoryEntry("GC://" + rootDsePath.Properties["rootDomainNamingContext"][0]);
            DirectoryEntry rootDse = new DirectoryEntry("LDAP://" + rootDsePath.Properties["defaultNamingContext"][0]);
            Diagnostics.Trace("GetAdUsers", "Connected to the root AD object");

            // Initialize a searcher object
            string searchString = "(&(objectclass=user)(objectcategory=Person)(displayName=" + filter + "*))";
            DirectorySearcher searcher = new DirectorySearcher(
                rootDse,
                searchString,
                new string[] { "displayName", "mail" },
                SearchScope.Subtree);
            Diagnostics.Trace("GetAdUsers", "Search submitted: " + searchString);

            // Do the search and return
            SearchResultCollection result = searcher.FindAll();

            // Log result
            if (result != null)
                Diagnostics.Trace("GetAdMailboxObjects", "Returned " + result.Count + "mailbox objects");
            else
                Diagnostics.Trace("GetAdMailboxObjects", "Returned null result set");

            // Transform the results
            ArrayList resultArray = new ArrayList();
            for (int i = 0; i < result.Count; i++)
            {
                // Retrieve the object's properties
                PropertyCollection properties = result[i].GetDirectoryEntry().Properties;
                
                // Add it to the array
                if (properties["mail"].Value != null && properties["displayName"].Value != null)
                {
                    resultArray.Add(new KeyValuePair<string, string>(
                        properties["mail"].Value.ToString(),
                        properties["displayName"].Value.ToString()));
                }
            }

            // Return
            return resultArray;
        }
    }
}
